#include "ReadDiscreteCoilRegisterCmd.h"

ReadDiscreteCoilRegisterCmd::ReadDiscreteCoilRegisterCmd(QObject *parent) :
    BaseModbusCmd(parent)
{
    this->m_protocolType = ProtocolType::ModbusProtocol;
    this->m_functionCode = FunctionCode;
}

Package ReadDiscreteCoilRegisterCmd::toPackage()
{
    Package package;
    QByteArray head,body;

    quint8  deviceAddress = m_modbusControl.deviceAddress();
    quint16 registerStartAddress = m_modbusControl.registerStartAddress();
    quint16 registerNumber = m_modbusControl.registerNumber();

    head.append(DataTypeConver::intToByteArray(deviceAddress,1));
    body.append(DataTypeConver::intToByteArray(registerStartAddress,2));
    body.append(DataTypeConver::intToByteArray(registerNumber,2));

    package.setHead(head);
    package.setFunction(FunctionCode);
    package.setBody(body);

    return package;
}

void ReadDiscreteCoilRegisterCmd::unPackage(Package package)
{
    quint8 deviceAddress = package.head().toHex().toInt(0,16);
    QByteArray body = package.body();
    QList<quint16> registrValueList;

    quint16 index = 0;
    quint16 byteNumber = body.mid(index,1).toHex().toInt(0,16);
    index += 1;
    for(int i=0; i<byteNumber; i++)
    {
        quint16 registrValue = body.mid(index,1).toHex().toInt(0,16);
        index += 1;
        registrValueList.append(registrValue);
    }

    m_cmdId = package.id();
    m_modbusControl.setDeviceAddress(deviceAddress);
    m_modbusControl.setFunctionCode(package.function());
    m_modbusControl.setRegistrValueList(registrValueList);
}

